package org.spider.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.spider.model.entity.SpiderDictEntity;
import org.spider.mapper.SpiderDictMapper;
import org.spider.model.vo.SpiderDictVO;
import org.spider.service.SpiderDictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springblade.core.tool.node.ForestNodeMerger;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringPool;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

import static org.spider.cache.CacheNames.DICT_LIST;
import static org.spider.cache.CacheNames.DICT_VALUE;

/**
 * <p>
 * 字典表 服务实现类
 * </p>
 *
 * @author lzy
 * @since 2022-06-20 19:04:14
 */
@Service
@Slf4j
public class SpiderDictServiceImp extends ServiceImpl<SpiderDictMapper, SpiderDictEntity> implements SpiderDictService {

    @Override
    public IPage<SpiderDictVO> selectDictPage(IPage<SpiderDictVO> page, SpiderDictVO dict) {
        return page.setRecords(baseMapper.selectDictPage(page, dict));
    }

    @Override
    public List<SpiderDictVO> tree() {
        return ForestNodeMerger.merge(baseMapper.tree());
    }

    @Override
    @Cacheable(cacheNames = DICT_VALUE, key = "#code+'_'+#dictKey")
    public String getValue(String code, Integer dictKey) {
        return Func.toStr(baseMapper.getValue(code, dictKey), StringPool.EMPTY);
    }

    @Override
    @Cacheable(cacheNames = DICT_LIST, key = "#code")
    public List<SpiderDictEntity> getList(String code) {
        return baseMapper.getList(code);
    }

    @Override
    @CacheEvict(cacheNames = {DICT_LIST, DICT_VALUE}, allEntries = true)
    public boolean submit(SpiderDictEntity dict) {
        LambdaQueryWrapper<SpiderDictEntity> lqw = Wrappers.<SpiderDictEntity>query().lambda().eq(SpiderDictEntity::getDictCode, dict.getDictCode()).eq(SpiderDictEntity::getDictKey, dict.getDictKey());
        Long cnt = baseMapper.selectCount((Func.isEmpty(dict.getId())) ? lqw : lqw.notIn(SpiderDictEntity::getId, dict.getId()));
        if (cnt > 0) {
            log.error("当前字典键值已存在!dict:{}", dict);
        }
        return saveOrUpdate(dict);
    }
}
